<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车 - 手机商城</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f8fafc;
            min-height: 100vh;
            color: #2c3e50;
        }

        .main-container {
            display: flex;
            min-height: 100vh;
        }

        /* 左侧导航栏 */
        .sidebar {
            width: 250px;
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
        }

        .sidebar-header {
            padding: 2rem 1.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
            color: white;
        }

        .logo-icon {
            font-size: 2rem;
        }

        .site-title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }

        .site-subtitle {
            opacity: 0.8;
            font-size: 0.9rem;
        }

        .sidebar-nav {
            padding: 1rem 0;
        }

        .nav-item {
            display: block;
            padding: 1rem 1.5rem;
            color: rgba(255,255,255,0.9);
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        .nav-item:hover {
            background: rgba(255,255,255,0.1);
            color: white;
        }

        .nav-item.active {
            background: rgba(52, 152, 219, 0.2);
            border-left-color: #3498db;
            color: white;
        }

        .nav-icon {
            margin-right: 0.75rem;
            width: 20px;
            display: inline-block;
        }

        .user-section {
            padding: 1rem 1.5rem;
            border-top: 1px solid rgba(255,255,255,0.1);
            margin-top: auto;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            margin-bottom: 1rem;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: #3498db;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        .user-details {
            flex: 1;
        }

        .user-name {
            font-weight: 600;
            font-size: 0.9rem;
        }

        .user-role {
            font-size: 0.8rem;
            opacity: 0.7;
        }

        .auth-btn {
            width: 100%;
            background: #3498db;
            color: white;
            border: none;
            padding: 0.75rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            text-align: center;
            display: block;
        }

        .auth-btn:hover {
            background: #2980b9;
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 2rem;
        }

        .content-header {
            background: white;
            padding: 1.5rem 2rem;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            margin-bottom: 2rem;
        }

        .page-title {
            font-size: 2rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .page-description {
            color: #7f8c8d;
            font-size: 1.1rem;
        }

        .cart-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            overflow: hidden;
        }

        .cart-header {
            background: #f8f9fa;
            padding: 1.5rem 2rem;
            border-bottom: 1px solid #e9ecef;
        }

        .cart-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .cart-items {
            padding: 0;
        }

        .cart-item {
            display: flex;
            align-items: center;
            padding: 1.5rem 2rem;
            border-bottom: 1px solid #f1f3f4;
            transition: background-color 0.3s;
        }

        .cart-item:hover {
            background: #f8f9fa;
        }

        .cart-item:last-child {
            border-bottom: none;
        }

        .item-info {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .item-icon {
            font-size: 2rem;
            background: #f8f9fa;
            padding: 0.5rem;
            border-radius: 8px;
            color: #3498db;
        }

        .item-details h3 {
            color: #2c3e50;
            margin-bottom: 0.25rem;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .item-price {
            color: #e74c3c;
            font-weight: 600;
            font-size: 1rem;
        }

        .quantity-controls {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin: 0 2rem;
        }

        .quantity-btn {
            background: #3498db;
            color: white;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
        }

        .quantity-btn:hover {
            background: #2980b9;
            transform: scale(1.1);
        }

        .quantity-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
        }

        .quantity-display {
            min-width: 40px;
            text-align: center;
            font-weight: 600;
            color: #2c3e50;
        }

        .remove-btn {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
        }

        .remove-btn:hover {
            background: #c0392b;
            transform: translateY(-1px);
        }

        .cart-summary {
            background: #f8f9fa;
            padding: 2rem;
            border-top: 1px solid #e9ecef;
        }

        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }

        .summary-row.total {
            font-weight: 700;
            font-size: 1.3rem;
            color: #2c3e50;
            border-top: 2px solid #e9ecef;
            padding-top: 1rem;
            margin-top: 1rem;
        }

        .checkout-btn {
            width: 100%;
            background: #3498db;
            color: white;
            border: none;
            padding: 1rem;
            border-radius: 8px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 1rem;
        }

        .checkout-btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }

        .checkout-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
        }

        .empty-cart {
            text-align: center;
            padding: 4rem 2rem;
            color: #7f8c8d;
        }

        .empty-icon {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }

        .empty-message {
            font-size: 1.2rem;
            margin-bottom: 2rem;
        }

        .shop-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 1rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            transition: all 0.3s;
        }

        .shop-btn:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }

        .loading {
            text-align: center;
            padding: 4rem 2rem;
            color: #7f8c8d;
        }

        .loading-spinner {
            font-size: 3rem;
            animation: spin 1s linear infinite;
            margin-bottom: 1rem;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .message {
            position: fixed;
            top: 2rem;
            right: 2rem;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            font-weight: 500;
            z-index: 1000;
            transform: translateX(400px);
            transition: transform 0.3s;
            max-width: 350px;
        }

        .message.show {
            transform: translateX(0);
        }

        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s;
            }

            .sidebar.open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
                padding: 1rem;
            }

            .cart-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }

            .quantity-controls {
                margin: 0;
            }

            .message {
                right: 1rem;
                left: 1rem;
                transform: translateY(-100px);
                max-width: none;
            }

            .message.show {
                transform: translateY(0);
            }
        }

        /* 移动端菜单按钮 */
        .mobile-menu-btn {
            display: none;
            position: fixed;
            top: 1rem;
            left: 1rem;
            z-index: 1001;
            background: #3498db;
            color: white;
            border: none;
            padding: 0.75rem;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1.2rem;
        }

        @media (max-width: 768px) {
            .mobile-menu-btn {
                display: block;
            }
        }
    </style>
</head>
<body>
    <div class="main-container">
        <!-- 左侧导航栏 -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="index.html" class="logo">
                    <span class="logo-icon">📱</span>
                </a>
                <div class="site-title">智能手机商城</div>
                <div class="site-subtitle">精选优质手机产品</div>
            </div>

            <nav class="sidebar-nav">
                <a href="index.html" class="nav-item">
                    <span class="nav-icon"></span>
                    首页商城
                </a>
                <a href="cart.html" class="nav-item active">
                    <span class="nav-icon"></span>
                    购物车
                </a>
                <a href="orders.html" class="nav-item">
                    <span class="nav-icon"></span>
                    我的订单
                </a>
            </nav>

            <div class="user-section">
                <div class="user-info" id="userInfoSection" style="display: none;">
                    <div class="user-avatar"></div>
                    <div class="user-details">
                        <div class="user-name" id="userName">用户</div>
                        <div class="user-role">普通用户</div>
                    </div>
                </div>
                <a href="login.html" class="auth-btn" id="authBtn">登录</a>
            </div>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 页面标题 -->
            <div class="content-header">
                <h1 class="page-title">购物车</h1>
                <p class="page-description">管理您选中的商品，随时调整数量或移除商品</p>
            </div>

            <!-- 购物车内容 -->
            <div class="cart-container">
                <!-- 加载状态 -->
                <div id="loadingIndicator" class="loading" style="display: none;">
                    <div class="loading-spinner"></div>
                    <div>正在加载购物车...</div>
                </div>

                <!-- 购物车项目 -->
                <div id="cartContent" style="display: none;">
                    <div class="cart-header">
                        <h2 class="cart-title">购物车商品</h2>
                    </div>
                    <div class="cart-items" id="cartItems">
                        <!-- 购物车项目将在这里动态加载 -->
                    </div>
                    <div class="cart-summary">
                        <div class="summary-row">
                            <span>商品总数：</span>
                            <span id="totalItems">0</span>
                        </div>
                        <div class="summary-row total">
                            <span>总计：</span>
                            <span id="totalPrice">¥0.00</span>
                        </div>
                        <button class="checkout-btn" id="checkoutBtn" onclick="checkout()">结算</button>
                    </div>
                </div>

                <!-- 空购物车 -->
                <div id="emptyCart" class="empty-cart" style="display: none;">
                    <div class="empty-icon">🛒</div>
                    <div class="empty-message">您的购物车是空的</div>
                    <a href="index.html" class="shop-btn">去购物</a>
                </div>
            </div>
        </main>
    </div>

    <!-- 移动端菜单按钮 -->
    <button class="mobile-menu-btn" id="mobileMenuBtn">☰</button>

    <!-- 消息提示 -->
    <div id="message" class="message"></div>

    <script>
        let currentUser = null;
        let cartItems = [];
        let products = [];

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeAuth();
            initializeMobileMenu();
        });

        // 初始化认证状态
        function initializeAuth() {
            const userData = localStorage.getItem('currentUser');
            if (userData) {
                currentUser = JSON.parse(userData);
                document.getElementById('userInfoSection').style.display = 'flex';
                document.getElementById('userName').textContent = currentUser.username;
                document.getElementById('authBtn').textContent = '退出登录';
                document.getElementById('authBtn').href = '#';
                document.getElementById('authBtn').onclick = logout;
                
                // 先加载商品信息，再加载购物车
                loadProducts().then(() => {
                    loadCart();
                });
            } else {
                showEmptyCart();
            }
        }

        // 初始化移动端菜单
        function initializeMobileMenu() {
            const mobileMenuBtn = document.getElementById('mobileMenuBtn');
            const sidebar = document.getElementById('sidebar');

            mobileMenuBtn.addEventListener('click', function() {
                sidebar.classList.toggle('open');
            });

            document.querySelector('.main-content').addEventListener('click', function() {
                sidebar.classList.remove('open');
            });
        }

        // 加载商品信息
        async function loadProducts() {
            try {
                const response = await fetch('/products');
                if (response.ok) {
                    products = await response.json();
                    return products;
                } else {
                    throw new Error('加载商品信息失败');
                }
            } catch (error) {
                console.error('加载商品信息错误:', error);
                throw error;
            }
        }

        // 加载购物车
        async function loadCart() {
            if (!currentUser) {
                showEmptyCart();
                return;
            }

            showLoading(true);

            try {
                const response = await fetch(`/carts/user/${currentUser.userId}`);
                if (response.ok) {
                    cartItems = await response.json();
                    
                    if (cartItems.length > 0) {
                        // 确保商品信息已加载
                        if (products.length === 0) {
                            await loadProducts();
                        }
                        renderCart();
                    } else {
                        showEmptyCart();
                    }
                } else {
                    showEmptyCart();
                }
            } catch (error) {
                console.error('加载购物车错误:', error);
                showMessage('加载购物车失败，请稍后重试', 'error');
                showEmptyCart();
            } finally {
                showLoading(false);
            }
        }

        // 渲染购物车
        function renderCart() {
            const container = document.getElementById('cartItems');
            let html = '';
            let totalItems = 0;
            let totalPrice = 0;

            if (cartItems.length === 0) {
                showEmptyCart();
                return;
            }

            cartItems.forEach(item => {
                const product = products.find(p => p.productId === item.productId);
                
                if (product) {
                    const itemTotal = product.productPrice * item.quantity;
                    totalItems += item.quantity;
                    totalPrice += itemTotal;

                    html += `
                        <div class="cart-item">
                            <div class="item-info">
                                <div class="item-icon">📱</div>
                                <div class="item-details">
                                    <h3>${product.productName}</h3>
                                    <div class="item-price">¥${product.productPrice.toFixed(2)}</div>
                                </div>
                            </div>
                            <div class="quantity-controls">
                                <button class="quantity-btn" onclick="updateQuantity(${item.cartId}, ${item.quantity - 1})" ${item.quantity <= 1 ? 'disabled' : ''}>-</button>
                                <span class="quantity-display">${item.quantity}</span>
                                <button class="quantity-btn" onclick="updateQuantity(${item.cartId}, ${item.quantity + 1})">+</button>
                            </div>
                            <button class="remove-btn" onclick="removeFromCart(${item.cartId})">移除</button>
                        </div>
                    `;
                } else {
                    // 即使没有找到商品信息，也显示基本信息
                    html += `
                        <div class="cart-item">
                            <div class="item-info">
                                <div class="item-icon"></div>
                                <div class="item-details">
                                    <h3>商品ID: ${item.productId}</h3>
                                    <div class="item-price">价格加载中...</div>
                                </div>
                            </div>
                            <div class="quantity-controls">
                                <button class="quantity-btn" onclick="updateQuantity(${item.cartId}, ${item.quantity - 1})" ${item.quantity <= 1 ? 'disabled' : ''}>-</button>
                                <span class="quantity-display">${item.quantity}</span>
                                <button class="quantity-btn" onclick="updateQuantity(${item.cartId}, ${item.quantity + 1})">+</button>
                            </div>
                            <button class="remove-btn" onclick="removeFromCart(${item.cartId})">移除</button>
                        </div>
                    `;
                    totalItems += item.quantity;
                }
            });

            container.innerHTML = html;
            document.getElementById('totalItems').textContent = totalItems;
            document.getElementById('totalPrice').textContent = `¥${totalPrice.toFixed(2)}`;
            
            document.getElementById('cartContent').style.display = 'block';
            document.getElementById('emptyCart').style.display = 'none';
        }

        // 显示空购物车
        function showEmptyCart() {
            document.getElementById('cartContent').style.display = 'none';
            document.getElementById('emptyCart').style.display = 'block';
        }

        // 显示加载状态
        function showLoading(show) {
            document.getElementById('loadingIndicator').style.display = show ? 'block' : 'none';
        }

        // 更新数量
        async function updateQuantity(cartId, newQuantity) {
            if (newQuantity < 1) return;

            try {
                const response = await fetch('/carts', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        cartId: cartId,
                        quantity: newQuantity
                    })
                });

                if (response.ok) {
                    loadCart(); // 重新加载购物车
                    showMessage('数量已更新', 'success');
                } else {
                    showMessage('更新失败，请重试', 'error');
                }
            } catch (error) {
                console.error('更新数量错误:', error);
                showMessage('网络错误，请稍后重试', 'error');
            }
        }

        // 从购物车移除
        async function removeFromCart(cartId) {
            if (!confirm('确定要移除这个商品吗？')) return;

            try {
                const response = await fetch(`/carts/${cartId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    loadCart(); // 重新加载购物车
                    showMessage('商品已移除', 'success');
                } else {
                    showMessage('移除失败，请重试', 'error');
                }
            } catch (error) {
                console.error('移除商品错误:', error);
                showMessage('网络错误，请稍后重试', 'error');
            }
        }

        // 结算
        async function checkout() {
            if (!currentUser || cartItems.length === 0) return;

            const checkoutBtn = document.getElementById('checkoutBtn');
            checkoutBtn.disabled = true;
            checkoutBtn.textContent = '结算中...';

            try {
                // 为每个购物车项目创建订单
                for (const item of cartItems) {
                    const response = await fetch('/orders', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            userId: currentUser.userId,
                            productId: item.productId,
                            quantity: item.quantity
                        })
                    });

                    if (!response.ok) {
                        throw new Error('创建订单失败');
                    }
                }

                // 清空购物车
                for (const item of cartItems) {
                    await fetch(`/carts/${item.cartId}`, {
                        method: 'DELETE'
                    });
                }

                showMessage('结算成功！订单已创建', 'success');
                setTimeout(() => {
                    window.location.href = 'orders.html';
                }, 2000);

            } catch (error) {
                console.error('结算错误:', error);
                showMessage('结算失败，请稍后重试', 'error');
            } finally {
                checkoutBtn.disabled = false;
                checkoutBtn.textContent = '结算';
            }
        }

        // 登出
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                window.location.reload();
            }
        }

        // 显示消息
        function showMessage(text, type = 'success') {
            const messageEl = document.getElementById('message');
            messageEl.textContent = text;
            messageEl.className = `message ${type} show`;

            setTimeout(() => {
                messageEl.classList.remove('show');
            }, 5000);
        }
    </script>
</body>
</html> 